package com.sgcc.dao;

import com.sgcc.mapper.UserMapper;
import com.sgcc.po.User;
import org.apache.ibatis.io.Resources;
import org.apache.ibatis.session.SqlSession;
import org.apache.ibatis.session.SqlSessionFactory;
import org.apache.ibatis.session.SqlSessionFactoryBuilder;

import java.io.InputStream;
import java.util.List;

public class UserDao {


    public SqlSession load()throws  Exception  {
        //mybatis的配置文件
        String resource = "SqlMapConfig.xml";
        //使用类加载器加载mybatis的配置文件（它也加载关联的映射文件）
        InputStream inputStream = Resources.getResourceAsStream(resource);
        //构建sqlSession的工厂
        SqlSessionFactory sessionFactory = new SqlSessionFactoryBuilder().build(inputStream);
        //使用MyBatis提供的Resources类加载mybatis的配置文件（它也加载关联的映射文件）
        //Reader reader = Resources.getResourceAsReader(resource);
        //构建sqlSession的工厂
        //SqlSessionFactory sessionFactory = new SqlSessionFactoryBuilder().build(reader);
        //创建能执行映射文件中sql的sqlSession
        SqlSession session = sessionFactory.openSession();

        return session;

    }

    public User login(User user) throws Exception {

        SqlSession session = load();
        /**
         * 映射sql的标识字符串，
         * me.gacl.mapping.userMapper是userMapper.xml文件中mapper标签的namespace属性的值，
         * getUser是select标签的id属性值，通过select标签的id属性值就可以找到要执行的SQL
         */
        /*String statement = "com.sgcc.mapper.UserMapper.login";//映射sql的标识字符串
        //执行查询返回一个唯一user对象的sql
        User user1 = session.selectOne(statement, user);*/

        UserMapper userMapper = session.getMapper(UserMapper.class);
        User user1 = userMapper.login(user);

        session.commit();
        session.close();
        return user1;
    }
    public List<User> listAll()throws Exception {

        SqlSession session = load();

        UserMapper userMapper = session.getMapper(UserMapper.class);
        List<User> userList= userMapper.listAll();

        session.commit();
        session.close();
        return userList;
    }
}

